package cn.org.wangchangjiu.sqltomongo.core.common;

import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;

import java.util.List;
import java.util.Objects;

@Data
public class MongoParserResultForCreateTable {
    /**
     * 集合名称
     */
    private String collectionName;

    /**
     * 字段约束
     */
    private Document properties;

    /**
     * 哪些字段是必须的
     */
    private List<String> required;

    /**
     * 索引
     */
    private List<MongoIndex> indexes;

    public String getPropertiesJson(){
        if(!Objects.isNull(this.properties)){
            return this.properties.toJson();
        }
        return "";
    }

    public String getRequiredJson(){
        StringBuilder sb = new StringBuilder();
        if(!CollectionUtils.isEmpty(this.required)){
            this.required.stream().forEach(doc -> sb.append("\""+doc+"\"").append(","));
            sb.deleteCharAt(sb.lastIndexOf(","));
        }
        return sb.toString();
    }

    private String getIndexJson() {
        StringBuilder sb = new StringBuilder();
        if(!CollectionUtils.isEmpty(this.indexes)){
            this.indexes.forEach(doc -> sb.append("db.").append(collectionName).append(".createIndex(").append(doc.toJson(collectionName)).append(");"));
        }
        return sb.toString();
    }

    public String toJsonString(){
        return String.format("db.createCollection(\"%s\",{validator:{$jsonSchema:{bsonType: \"object\""
                +(CollectionUtils.isEmpty(required)?"":String.format(",required: [%s]",getRequiredJson()))+",properties:%s}},validationAction:\"error\"});"
                +"%s", collectionName,getPropertiesJson(),getIndexJson());
    }
}
